package com.artifex.mupdf.viewer

import android.content.Context
import com.google.gson.Gson
import androidx.core.content.edit

class SentencePatternManager(context: Context, scope: String) {
    private val prefs = context.getSharedPreferences(scope, Context.MODE_PRIVATE)
    private val gson = Gson()

    private val _patterns = mutableListOf<SentencePattern>().apply {
        addAll(getDefaultPatterns())
    }
    val patterns: List<SentencePattern> get() = _patterns

    init {
        loadPatterns()
    }

    fun removePattern(index: Int) {
        _patterns.removeAt(index)
        savePatterns()
    }

    private fun getDefaultPatterns(): List<SentencePattern> {
        return listOf(
            SentencePattern(
                regex = "\\b[A-Z]{2,}\\b",
                name = "NAME",
                isEnabled = false,
            ),
            SentencePattern(
                regex = "\\s*(Chapter\\s+[A-Za-z0-9-]+)\\s*",
                name = "Chapter",
                isEnabled = false,
            ),
//            SentencePattern(
//                regex = "\\b(?=Part})",
//                name = "Chapter",
//            ),
//            SentencePattern(
//                regex = "(?<=Part\\s[A-Za-z0-9-]{1,10}})\\b",
//                name = "Chapter",
//            ),
//            SentencePattern(
//                regex = "\\b(?=(?:Chapter|Part)})",
//                name = "Chapter",
//            ),
//            SentencePattern(
//                regex = "(?<=(?:Chapter|Part)\\s[A-Za-z0-9-]{1,10}})\\b",
//                name = "Chapter",
//            ),
//            SentencePattern(
//                regex = "\\b(?=\\p{Lu})",
//                name = "Word boundary followed by upper Case",
//                description = "Splits at all chapter markers (numeric and text)"
//            ),
            SentencePattern(
                regex = "(?ix)(?=\\s*(?:Chapter|Part)\\s+([0-9]+|[IVXLCDM]+|(?:[A-Za-z]+(?:-[A-Za-z]+)?))\\b)",
                name = "Advanced Chapter Detection",
                description = "Splits at all chapter markers (numeric and text)",
                isEnabled = false,
            ),
            SentencePattern(
                regex = "(?<=\\S.{0,14})\\n(?=\\p{Lu})",
                name = "Short Line Breaks",
                description = "Splits lines shorter than 15 characters followed by Upper Case Character"
            ),
            SentencePattern(
                regex = "[。！？!?]+",
                name = "Chinese Sentences",
            ),
            SentencePattern(
                regex = "(?<!\\b(?:Dr|Mr|Mrs|Ms|Prof|Inc|Ltd|Co|Corp|No|Vol|Fig|vs|approx|est|[A-Za-z]|Jan|Feb|Mar|Apr|Jun|Jul|Aug|Sep|Oct|Nov|Dec))[.?!\";][^\\W]?",
                name = "English Sentences",
            ),
//            SentencePattern(
//                regex = "(?<=[.!?])\\s+",
//                name = "Standard Sentences",
//                description = "Splits after .!? followed by whitespace"
//            ),
            SentencePattern(
//                regex = "(?<=\\n\\n)",
                regex = "[\\n\\r]{2,}",
                name = "Paragraph Breaks",
                description = "Treats double newlines as splits"
            )
        )
    }

//    fun getActivePatterns(): List<SentencePattern> {
//        return patterns.filter { it.isEnabled }.sortedBy { it.order }
//    }

//    fun getAllPatterns(): List<SentencePattern> {
//        return patterns.sortedBy { it.order }
//    }

    fun addPattern(pattern: SentencePattern) {
        _patterns.add(pattern.copy(order = patterns.size))
        savePatterns()
    }

    fun updatePattern(index: Int, updated: SentencePattern): Boolean {
        if(index > -1 && index < _patterns.size) {
            _patterns[index] = updated
            savePatterns()
            return true
        }
        return false
    }

    private fun savePatterns() {
        prefs.edit {
            putString("patterns", gson.toJson(_patterns))
            apply()
        }
    }

    fun loadPatterns() {
        val json = prefs.getString("patterns", null)
        json?.let {
            val saved = gson.fromJson(it, Array<SentencePattern>::class.java).toList()
            _patterns.clear()
            _patterns.addAll(saved)
        }
    }

    fun split(text: String): List<String> {
        var currentTexts = listOf(text)

        _patterns.forEach { pattern ->
            if (pattern.isEnabled) {
                currentTexts = currentTexts.flatMap { chunk ->
                    try {
                        chunk.split(pattern.regex.toRegex())
                    } catch (_: Exception) {
                        listOf(chunk) // fallback if pattern is invalid
                    }
                }
            }
        }

        return currentTexts.filter { it.isNotBlank() }
    }

//    fun splitWithMultiplePatterns(text: String, patterns: List<SentencePattern>): List<String> {
//        var currentTexts = listOf(text)
//
//        patterns.forEach { pattern ->
//            if (pattern.isEnabled) {
//                currentTexts = currentTexts.flatMap { chunk ->
//                    try {
//                        chunk.split(pattern.regex.toRegex())
//                    } catch (e: Exception) {
//                        listOf(chunk) // fallback if pattern is invalid
//                    }
//                }
//            }
//        }
//
//        return currentTexts.filter { it.isNotBlank() }
//    }
//
//    fun splitWithCombinedPattern(text: String, patterns: List<SentencePattern>): List<String> {
//        val activePatterns = patterns.filter { it.isEnabled }
//        if (activePatterns.isEmpty()) return listOf(text)
//
//        return text.split(activePatterns.joinToString("|") { "(${it.regex})" }.toRegex())
//    }
}